package middleware

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"net/http"
	"one-wiki/commons"
	"runtime"
)

func ExceptionMiddleware() gin.HandlerFunc {
	return Exception
}
func Exception(c *gin.Context) {
	defer func() {
		if err := recover(); err != nil {
			fmt.Printf("%v", err)
			var buf [4096]byte
			n := runtime.Stack(buf[:], false)
			fmt.Printf("Stack trace:\n%s", buf[:n])

			switch v := err.(type) {
			case commons.RequestError:
				// 符合预期的错误，可以直接返回给客户端
				c.AbortWithStatusJSON(v.Code(), v.Msg)
			case error:
				c.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"error": "server error"})
			default:
				c.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"error": "server error"})
			}
		}
	}()
	c.Next()

}
